package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.tabhome

import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.IApiProcessCallback
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.createApiAction
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.doPostRequest
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.login.LoginGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.permissions.PermissionGhanaSplashActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.user.mainProcessFormat
import com.helasasa.maxfunds.lineofcredit.cashloan.utils.analytics.util.AnalyticsUtil
import org.json.JSONArray
import org.json.JSONObject

class TabHomeGhanaViewModel : ViewModel() {

    private val _loadingResult = MutableLiveData<Boolean>()
    val loadingResult: LiveData<Boolean> = _loadingResult

    private val _pageDetailResult = MutableLiveData<TabHomeGhanaResult>()
    val pageDetailResult: LiveData<TabHomeGhanaResult> = _pageDetailResult

    private val _mainProcessResult = MutableLiveData<TabHomeGhanaMainProcessResult>()
    val mainProcessResult: LiveData<TabHomeGhanaMainProcessResult> = _mainProcessResult

    private val _nextRouterResult =
        MutableLiveData<TabHomeGhanaNextRouterResult<AppCompatActivity>>()
    val nextRouterResult: LiveData<TabHomeGhanaNextRouterResult<AppCompatActivity>> =
        _nextRouterResult

    /** 获取页面详情接口 */
    fun pageDetail() {
        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "Jdvrwau2zkjCCvwpptC8w"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                val customize = obj.optJSONObject("customize")
                if (customize != null) {
                    // 更新客服
                    val mobile = customize.optString("mobile")
                    val email = customize.optString("email")
                    ProjectApplication.updateHotlines(mobiles = mobile, emails = email)

                    // 更新首页额度
                    var homeAmount = customize.optString("homeAmount")
                    if (homeAmount.isBlank()) {
                        homeAmount = "300000"
                        customize.put("homeAmount", homeAmount)
                    }
                    ProjectApplication.updateHomeAmount(homeAmount)

                    // 更新权限
                    val permissions = customize.optJSONObject("permissions") ?: JSONObject()
                    val splashPer = permissions.optJSONArray("permission") ?: JSONArray()
                    val applyPer = permissions.optJSONArray("home") ?: JSONArray()
                    ProjectApplication.updateSplashPermissions(splashPer)
                    ProjectApplication.updateApplyPermissions(applyPer)

                    // 更新运营商列表-法语
                    val walletChannels = customize.optJSONArray("walletChannels") ?: JSONArray()
                    ProjectApplication.updateWalletChannels(walletChannels)

                    // 更新测试账号列表-法语
                    val accList = customize.optJSONArray("accListV2") ?: JSONArray()
                    ProjectApplication.updateAccUsers(accList)

                    _pageDetailResult.value = TabHomeGhanaResult(success = customize)
                } else {
                    _pageDetailResult.value = TabHomeGhanaResult(success = JSONObject())
                }
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _pageDetailResult.value = TabHomeGhanaResult(error = errMsg)
            }
        })

    }

    /** 查询主流程接口 */
    fun mainProcess() {
        _loadingResult.value =true

        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "D50PrK3UELaosdHcVCL7A"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value =false

                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                _mainProcessResult.value = TabHomeGhanaMainProcessResult(success = obj)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value =false

                _mainProcessResult.value = TabHomeGhanaMainProcessResult(error = errMsg)
            }
        })
    }

    /**
     * 点击申请
     */
    fun startApply() {
        // 1判断权限
        val perList = mutableListOf(
            android.Manifest.permission.READ_SMS,
            android.Manifest.permission.READ_PHONE_STATE
        )
        if (!checkPermissionsGranted(perList)) {
            _nextRouterResult.value =
                TabHomeGhanaNextRouterResult(nextPage = PermissionGhanaSplashActivity::class.java)
            return
        }

        // 2判断登录
        if (!ProjectApplication.onActionReady()) {
            _nextRouterResult.value =
                TabHomeGhanaNextRouterResult(nextPage = LoginGhanaActivity::class.java)
            return
        }

        try {
            AnalyticsUtil.saveDeviceS2SInfo()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        // 3判断流程
        mainProcess()
    }

    /**
     * 检查权限是否同意
     */
    private fun checkPermissionsGranted(permissionList: List<String>): Boolean {
        val isNotAllGranted = permissionList.any {
            PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                ProjectApplication.instance,
                it
            )
        }
        return !isNotAllGranted
    }

    /** 页面跳转 */
    fun nextRouter(jsonObject: JSONObject) {
        // 判断下一步
        val nextRouterResult = jsonObject.mainProcessFormat(fromTabHome = true)
        if (nextRouterResult.nextRouter != null) {
            _nextRouterResult.value =
                TabHomeGhanaNextRouterResult(nextPage = nextRouterResult.nextRouter)
        }
    }

}